<?php
/* 
 *客户询单
 */
class InquiryAction extends CommonAction {
    public function _filter(&$map) {
        $key = trim($_REQUEST['keywords']);
        if(!empty($key)) {
            $where['Product.name'] = array('like',"%".$key."%");
            $where['Product.ename'] = array('like',"%".$key."%");
            $where['Product.cas'] = array('like',"%".$key."%");
            
            $where['Inquiry.mano'] = array('like',"%".$key."%");
            $where['_logic'] = "or";
            $map['_complex'] = $where;
        }
        //按询价单状态搜索
        if( $_REQUEST['ask_status'] != '' ){
            $map['Ask_supplier.status'] = $_REQUEST['ask_status'] ;
        }
        if(!empty($_REQUEST['customer']))
            $map['Customer.name'] = array('like',"%".trim($_REQUEST['customer'])."%");

        if($_REQUEST['charge_man'] != '' )
            $map['Inquiry.charge_man'] = $_REQUEST['charge_man'];

        if(!empty($_REQUEST['ask_mano']))
            $map['Ask_supplier.mano'] = array('like',"%".trim($_REQUEST['ask_mano'])."%");

    }

    public function index()
    { if( $_REQUEST['ask_status'] != '' || !empty($_REQUEST['ask_mano']) ){
        parent::index('InquiryAskView');
        }
      else
        parent::index('InquiryView');
    }

    public function _before_edit(){
        $this->assign('users',getModelIdName('User'));
    }

    public function insert()
    {
        if(!empty($_POST['product_id']))
            $_POST['product_name'] = getModelName($_POST['product_id'],'Product','name'); 
        else{//新增产品
            if(empty($_POST['ename']) || empty($_POST['cas'])) //必须录入英文名
                $this->error('请选择或添加产品!英文名及CAS号必须输入！');

            $pdata['name'] =  trim($_POST['product_name']);   //中文名
            $pdata['ename'] =  trim($_POST['ename']); //ename
            $pdata['cas'] =  trim($_POST['cas']);
            $pdata['unit_id'] =  1; //默认KG
            $pdata['create_time'] =  time();

            $pid = 0;
            if(!empty($_POST['cas'])){
                $r = M('Product')->getByCas(trim($_POST['cas']));
                if($r){
                    $pid = $r['id'];
                    $_POST['product_name'] = $r['name'];
                }
                    
            }  
            else if( $rs = M('Product')->getByEname(trim($_POST['ename'])) ){
                //$rs = M('Product')->getByEname($_POST['ename']);
                $pid = $rs['id'];
                $_POST['product_name'] = $rs['name'];
            }     
            
            if(!$pid){
                $pid = M('Product')->data($pdata)->add();  //直接add，会对产品名中的单引号进行反转义.需修改TP核心转义类
                //add new product
                
            }
                
            if(!$pid)
                $this->error('新产品添加失败，请重新添加！');
               

            $_POST['product_id'] = $pid;
        }
        $_POST['charge_man'] = $_POST['user_id']; //初始化时，负责人与经办人相同

        $jumpUrl = __APP__.'/Inquiry';
        $name='Inquiry';
        $model = D ($name);
        if (false === $model->create ()) {
            $this->error ( $model->getError () );
        }
        //保存当前数据对象
        $list=$model->add ();
        if ($list!==false) { //保存成功
            //日志记录
             $mod_field = getModelName ($list, $name,$field);
            //如果未取到字段值 ，则返回对应的ID编号
            $msg = '新增 '.$name.': '.$mod_field.' (编号：'.$list.')';
            if('Action' != $name)
                A('Action')->writeLog($msg,'新增',$name,$list);
            if(empty($jumpUrl))
                $jumpUrl = Cookie::get ( '_currentUrl_' );
            //创建采购询价任务单
            if($_POST['donext'] == 1 ){
                $this->redirect('/Ask_supplier/add', 
                    array('inquiry_id'=>$list,
                        'product_id'=>$_POST['product_id'],
                        'number'=>$_POST['number'],
                        'unit_id' => $_POST['unit_id'],
                        'specification' => $_POST['quality'],
                        'delivery_date' => $_POST['delivery_date'],
                        'remark' => $_POST['remark'],
                        ),
                            1,'<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />询单创建成功！1秒后将创建采购询价单~~');
            }else{
                $this->assign ( 'jumpUrl',  $jumpUrl);
                $this->success ('新增成功!');
            }
        } else {
            //失败提示
            $this->error ('新增失败!');
        }
        
        }
      
    
    public function _before_update()
    {

        if($_POST['status'] == 1 ){
            $Ask_supplier = M('Ask_supplier');
             $Ask_supplier->getByInquiry_id($_POST['id'] );
             if(!empty($Ask_supplier) )
                $Ask_supplier->setField('status',3); //设为等待最终确认

        }

        //是否有采购询价,如有，则同步更新对应询价单的状态
        $ask_id = M('Ask_supplier')->where('inquiry_id ='.$_POST['id'])->getField('id',"");
        if( !empty($ask_id) )
            M('Ask_supplier')->where('id = '.$ask_id)->setField('status',$_POST['status']);
        //客户还价-待更新,同时将还盘要求也填写进去
        if($_POST['status'] == 6 and !empty($_POST['ask_supplier_id']) and !empty($_POST['ask_remark']) )
            M('Ask_supplier')->where('id ='.$_POST['ask_supplier_id'])->setField('remark',$_POST['ask_remark']);
   
    }


    //分配责任人
    public function charge()
    {
        $id = $_REQUEST['id'];
        if (isset ( $id )) {
          
            $condition = array ('id' => array ('in', explode ( ',', $id ) ) );
            $list = M('Inquiry') ->where ( $condition )->findAll();
            $sale_ids = array(); //有效的SALE_ID
            if(!is_array($list))
                $this->error('您选择的客户询单不存在！');
            $this->assign('receives',$list);
            $this->display();
        }else
          $this->error("请选择客户询单！");
    }

     //目前暂用于批量分配负责人
    public function mass_update()
    {
         $data = $_POST;
        $count_no = count($data['charge_man']);
        for($i =0; $i < $count_no;$i++) {
          $_POST['id'] =  $data['id'][$i];
        //批量指定负责人
        if(!empty($data['charge_man'][$i]))
            $_POST['charge_man'] = $data['charge_man'][$i];
        
            $this->micro_update($_POST['id']);

          unset($_POST);
        }

        $jumpUrl = $_REQUEST['jumpUrl'];
        if(empty($jumpUrl))
            $jumpUrl = Cookie::get ( '_currentUrl_' );
        $this->assign ( 'jumpUrl', $jumpUrl );
        $this->success ('批量修改成功!');
    }

    //业务报价
    public function inquiry_offer(){
       $inquiry_id = trim($_REQUEST['inquiry_id']);
       $ask_supplier_detail_id = trim($_REQUEST['ask_supplier_detail_id']);
       if(empty($_REQUEST['inquiry_id']) || empty($_REQUEST['ask_supplier_detail_id'] ) )
           $this->error("请先选择询单或采购询价！");
       $new_ask_supplier_id = M('Ask_supplier')->where('inquiry_id = '.$inquiry_id)->setField('status',5); //设采购询价单为已经报价
       $new_inquiry_id = M('Inquiry')->where('id = '.$inquiry_id)->setField('status',5); //设询单为已经报价
       $new_ask_detail_id = M('Ask_supplier_detail')->where('id = '.$ask_supplier_detail_id)->setField('sale_consult',2); //设置报价意见为 已经采用
       if( $new_ask_detail_id || $new_inquiry_id ||  $new_ask_supplie_id ){
           $jumpUrl = __APP__."/Inquiry/index/charge_man/".$_SESSION[C('USER_AUTH_KEY')]."/ask_status/4"; 
           $this->assign('jumpUrl',$jumpUrl);
           $this->success("报价成功！");
       }
       else 
           $this->error("报价失败！");

    }

}
?>
